using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using System.IO;
using System.Net;

namespace Mes.质检管理.ReinspectionCheck
{
    public partial class ReinspectionAdd : Form
    {
        private const string API_BASE_URL = "/api/Inspection";
        
        // 传入的参数
        public int InspectionId { get; set; }
        public string InspectionNo { get; set; }
        public string MaterialName { get; set; }
        
        public ReinspectionAdd()
        {
            InitializeComponent();
            InitializeControls();
        }
        
        private void InitializeControls()
        {
            // 初始化合格状态下拉框
            cmbQualificationStatus.Items.Clear();
            cmbQualificationStatus.Items.AddRange(new object[] { "合格", "不合格" });
            cmbQualificationStatus.SelectedIndex = 0;
            
            // 设置默认复检日期为今天
            dtpReinspectionDate.Value = DateTime.Now;
            
            // 生成默认复检编号
            txtReinspectionNo.SkinTxt.Text = GenerateReinspectionNo();
        }
        
        private string GenerateReinspectionNo()
        {
            return $"FJ{DateTime.Now:yyyyMMddHHmmss}";
        }
        
        private async void ReinspectionAdd_Load(object sender, EventArgs e)
        {
            try
            {
                await LoadInspectionData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private async Task LoadInspectionData()
        {
            if (InspectionId <= 0) return;
            
            try
            {
                // 加载质检基本信息
                await LoadBasicInfo();
                
                // 加载原料信息
                await LoadMaterialInfo();
            }
            catch (Exception ex)
            {
                throw new Exception($"加载质检数据失败：{ex.Message}");
            }
        }
        
        private async Task LoadBasicInfo()
        {
            try
            {
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetInspectionBasicById") + $"?Id={InspectionId}";
                
                using (var client = new HttpClient())
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    var response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<InspectorBasicModel>>(json);
                        
                        if (result?.code == 200 && result.data != null)
                        {
                            lblInspectionNoVal.Text = result.data.InspectionNo;
                            lblSupplierVal.Text = result.data.Supplier;
                            lblDateVal.Text = result.data.InspectionDate.ToString("yyyy-MM-dd");
                        }
                    }
                    else
                    {
                        // 处理错误响应
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"加载基本信息失败: {response.StatusCode} - {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载基本信息异常: {ex.Message}");
            }
        }
        
        private async Task LoadMaterialInfo()
        {
            try
            {
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetMaterialByInspectionId") + $"?InspectionId={InspectionId}";
                
                using (var client = new HttpClient())
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    var response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<MateriaMessageModel>>(json);
                        
                        if (result?.code == 200 && result.data != null)
                        {
                            lblMaterialNoVal.Text = result.data.MaterialNo;
                            lblMaterialNameVal.Text = result.data.MaterialName;
                        }
                    }
                    else
                    {
                        // 处理错误响应
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"加载原料信息失败: {response.StatusCode} - {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载原料信息异常: {ex.Message}");
            }
            
            // 加载质检详情
            await LoadInspectionDetail();
        }
        
        private async Task LoadInspectionDetail()
        {
            try
            {
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetDetailByInspectionId") + $"?InspectionId={InspectionId}";
                
                using (var client = new HttpClient())
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    var response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<InspectionDetailModel>>(json);
                        
                        if (result?.code == 200 && result.data != null)
                        {
                            lblInspectionQuantityVal.Text = result.data.InspectionQuantity.ToString();
                            lblInspectionResultVal.Text = result.data.InspectionResult;
                            
                            // 设置默认复检数量为原质检数量
                            txtReinspectionQuantity.SkinTxt.Text = result.data.InspectionQuantity.ToString();
                            
                            // 设置默认复检名称
                            txtReinspectionName.SkinTxt.Text = $"{MaterialName}复检";
                        }
                    }
                    else
                    {
                        // 处理错误响应
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"加载质检详情失败: {response.StatusCode} - {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载质检详情异常: {ex.Message}");
            }
        }
        
        private async void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ValidateForm())
                    return;
                
                await SaveReinspection();
                
                MessageBox.Show("复检信息保存成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private bool ValidateForm()
        {
            if (string.IsNullOrWhiteSpace(txtReinspectionNo.SkinTxt.Text))
            {
                MessageBox.Show("请输入复检编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtReinspectionNo.Focus();
                return false;
            }
            
            if (string.IsNullOrWhiteSpace(txtReinspectionName.SkinTxt.Text))
            {
                MessageBox.Show("请输入复检名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtReinspectionName.Focus();
                return false;
            }
            
            if (!int.TryParse(txtReinspectionQuantity.SkinTxt.Text, out int quantity) || quantity <= 0)
            {
                MessageBox.Show("请输入有效的复检数量", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtReinspectionQuantity.Focus();
                return false;
            }
            
            if (cmbQualificationStatus.SelectedIndex < 0)
            {
                MessageBox.Show("请选择合格状态", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbQualificationStatus.Focus();
                return false;
            }
            
            if (string.IsNullOrWhiteSpace(txtReinspector.SkinTxt.Text))
            {
                MessageBox.Show("请输入复检人", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtReinspector.Focus();
                return false;
            }
            
            return true;
        }
        
        private async Task SaveReinspection()
        {
            var command = new AddReinspectionCommand
            {
                ReinspectionNo = txtReinspectionNo.SkinTxt.Text.Trim(),
                ReinspectionName = txtReinspectionName.SkinTxt.Text.Trim(),
                ReinspectionQuantity = int.Parse(txtReinspectionQuantity.SkinTxt.Text),
                QualificationStatus = cmbQualificationStatus.Text,
                ReinspectionDate = dtpReinspectionDate.Value,
                Reinspector = txtReinspector.SkinTxt.Text.Trim(),
                Remarks = txtRemarks.SkinTxt.Text.Trim(),
                ChenckId = InspectionId
            };
            
            string url = HttpClientHelper.GetApiUrl("/api/Inspection/AddReinspection");
            string json = JsonConvert.SerializeObject(command);
            
            using (var client = new HttpClient())
            {
                // 设置超时时间
                client.Timeout = TimeSpan.FromSeconds(30);
                
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PostAsync(url, content);
                
                if (!response.IsSuccessStatusCode)
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    throw new Exception($"API调用失败：{response.StatusCode} - {errorContent}");
                }
                
                var responseJson = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<ApiResult<int>>(responseJson);
                
                if (result?.code != 200)
                {
                    throw new Exception(result?.message ?? "保存失败");
                }
            }
        }
        
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
    
    // 数据模型类
    public class ApiResult<T>
    {
        public int code { get; set; }
        public string message { get; set; }
        public T data { get; set; }
    }
    
    public class InspectorBasicModel
    {
        public string InspectionNo { get; set; }
        public string Supplier { get; set; }
        public DateTime InspectionDate { get; set; }
    }
    
    public class MateriaMessageModel
    {
        public string MaterialNo { get; set; }
        public string MaterialName { get; set; }
    }
    
    public class InspectionDetailModel
    {
        public int InspectionQuantity { get; set; }
        public string InspectionResult { get; set; }
    }
    
    public class AddReinspectionCommand
    {
        public string ReinspectionNo { get; set; }
        public string ReinspectionName { get; set; }
        public int ReinspectionQuantity { get; set; }
        public string QualificationStatus { get; set; }
        public DateTime ReinspectionDate { get; set; }
        public string Reinspector { get; set; }
        public string Remarks { get; set; }
        public int ChenckId { get; set; }
    }
}
